<template>
    <div class="logs-container">
        <!-- 统计卡片 -->
        <div class="mb10">
            <a-row :gutter="16">
                <a-col :span="6">
                    <a-card class="animate-on-enter">
                        <a-statistic title="总请求数" :value="statistics.total_requests"
                            :value-style="{ color: '#1890ff' }" />
                    </a-card>
                </a-col>
                <a-col :span="6">
                    <a-card class="animate-on-enter animate-delay-1">
                        <a-statistic title="成功请求" :value="statistics.success_requests"
                            :value-style="{ color: '#52c41a' }" />
                    </a-card>
                </a-col>
                <a-col :span="6">
                    <a-card class="animate-on-enter animate-delay-2">
                        <a-statistic title="失败请求" :value="statistics.failed_requests"
                            :value-style="{ color: '#ff4d4f' }" />
                    </a-card>
                </a-col>
                <a-col :span="6">
                    <a-card class="animate-on-enter animate-delay-3">
                        <a-statistic title="成功率" :value="statistics.success_rate" suffix="%"
                            :value-style="{ color: '#722ed1' }" />
                    </a-card>
                </a-col>
            </a-row>
        </div>

        <!-- 搜索表单 -->
        <div class="mb10 animate-on-enter animate-delay-4">
            <SearchForm :searchForm="searchForm" :searchFields="searchFields" :loading="loading" :maxFirstRowItems="3"
                @search="handleSearch" @reset="handleReset" />
        </div>

        <!-- 操作按钮 -->
        <div class="mb10 animate-on-enter animate-delay-5">
            <a-space>
                <a-button type="primary" danger @click="showClearModal">
                    <delete-outlined /> 清理日志
                </a-button>
                <a-button @click="refreshData">
                    <reload-outlined /> 刷新
                </a-button>
            </a-space>
        </div>

        <!-- 日志表格 -->
        <div class="card-wrap animate-on-enter animate-delay-6">
            <DataList ref="DataListRef" :api="(params) => getListByPage(params)" :columns="tableColumns">
                <template #user_type="{ record }">
                    <a-tag :color="getUserTypeColor(record.user_type)">{{ record.operator_type_text }}</a-tag>
                </template>
                <template #method="{ record }">
                    <a-tag :color="getMethodColor(record.method)">{{ record.method }}</a-tag>
                </template>
                <template #is_success="{ record }">
                    <a-tag :color="record.is_success ? 'success' : 'error'">
                        {{ record.is_success ? '成功' : '失败' }}
                    </a-tag>
                </template>
                <template #duration="{ record }">
                    <span :class="{ 'slow-request': record.duration > 1000 }">
                        {{ record.duration }}ms
                    </span>
                </template>
                <template #action="{ record }">
                    <a-button type="link" size="small" @click="showDetail(record)">
                        <eye-outlined /> 详情
                    </a-button>
                </template>
            </DataList>
        </div>

        <!-- 详情弹窗 -->
        <a-modal v-model:open="detailVisible" title="日志详情" width="800px" :footer="null">
            <div v-if="currentLog" class="log-detail">
                <a-descriptions :column="2" bordered>
                    <a-descriptions-item label="操作描述">{{ currentLog.description }}</a-descriptions-item>
                    <a-descriptions-item label="操作人">{{ currentLog.admin_name }}</a-descriptions-item>
                    <a-descriptions-item label="请求方法">
                        <a-tag :color="getMethodColor(currentLog.method)">{{ currentLog.method }}</a-tag>
                    </a-descriptions-item>
                    <a-descriptions-item label="请求URI">{{ currentLog.uri }}</a-descriptions-item>
                    <a-descriptions-item label="控制器">{{ currentLog.controller }}</a-descriptions-item>
                    <a-descriptions-item label="方法">{{ currentLog.action }}</a-descriptions-item>
                    <a-descriptions-item label="状态">
                        <a-tag :color="currentLog.is_success ? 'success' : 'error'">
                            {{ currentLog.is_success ? '成功' : '失败' }}
                        </a-tag>
                    </a-descriptions-item>
                    <a-descriptions-item label="响应时间">{{ currentLog.duration }}ms</a-descriptions-item>
                    <a-descriptions-item label="IP地址">{{ currentLog.ip }}</a-descriptions-item>
                    <a-descriptions-item label="操作时间">{{ currentLog.created_at }}</a-descriptions-item>
                </a-descriptions>

                <div class="request-data"
                    v-if="currentLog.request_data && Object.keys(currentLog.request_data).length > 0">
                    <h4>请求参数</h4>
                    <pre>{{ JSON.stringify(currentLog.request_data, null, 2) }}</pre>
                </div>

                <div class="user-agent" v-if="currentLog.user_agent">
                    <h4>用户代理</h4>
                    <p>{{ currentLog.user_agent }}</p>
                </div>
            </div>
        </a-modal>

        <!-- 清理日志弹窗 -->
        <a-modal v-model:open="clearVisible" title="清理日志" @ok="handleClearLogs" :confirm-loading="clearLoading">
            <a-radio-group v-model:value="clearType" style="margin-bottom: 16px">
                <a-radio :value="'days'">按天数清理</a-radio>
                <a-radio :value="'all'">清理全部</a-radio>
            </a-radio-group>

            <template v-if="clearType === 'days'">
                <p>请选择要清理多少天前的日志：</p>
                <a-input-number v-model:value="clearDays" :min="1" :max="365" style="width: 200px" /> 天
            </template>

            <template v-else>
                <p>将清理所有日志记录</p>
            </template>

            <p style="margin-top: 16px; color: #ff4d4f;">
                <exclamation-circle-outlined /> 此操作不可恢复，请谨慎操作！
            </p>
        </a-modal>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import {
    SearchOutlined,
    ReloadOutlined,
    DeleteOutlined,
    EyeOutlined,
    ExclamationCircleOutlined
} from '@ant-design/icons-vue'
import { getLogs, getLogDetail, clearLogs, getStatistics, getListByPage } from '@/api/logs'
import DataList from '@/components/DataList.vue'
import SearchForm from '@/components/SearchForm.vue'
import dayjs from 'dayjs'

// 响应式数据
const DataListRef = ref()
const loading = ref(false)
const statistics = ref({
    total_requests: 0,
    success_requests: 0,
    failed_requests: 0,
    success_rate: 0
})

// 搜索表单
const searchForm = reactive({
    user_type: undefined,
    method: undefined,
    controller: '',
    is_success: undefined,
    dateRange: [],
    start_date: '',
    end_date: ''
})

// 搜索字段定义
const searchFields = [
    {
        prop: 'user_type',
        label: '用户类型',
        type: 'select',
        placeholder: '选择用户类型',
        options: [
            { value: 'admin', label: '管理员' },
            { value: 'user', label: '用户' },
            { value: 'guest', label: '访客' }
        ]
    },
    {
        prop: 'method',
        label: '请求方法',
        type: 'select',
        placeholder: '选择请求方法',
        options: [
            { value: 'GET', label: 'GET' },
            { value: 'POST', label: 'POST' },
            { value: 'PUT', label: 'PUT' },
            { value: 'DELETE', label: 'DELETE' }
        ]
    },
    {
        prop: 'controller',
        label: '控制器',
        type: 'input',
        placeholder: '输入控制器名称'
    },
    {
        prop: 'is_success',
        label: '状态',
        type: 'select',
        placeholder: '选择状态',
        options: [
            { value: 1, label: '成功' },
            { value: 0, label: '失败' }
        ]
    },
    {
        prop: 'dateRange',
        label: '日期范围',
        type: 'daterange'
    }
]



// 详情弹窗
const detailVisible = ref(false)
const currentLog = ref(null)

// 清理弹窗
const clearVisible = ref(false)
const clearLoading = ref(false)
const clearDays = ref(30)
const clearType = ref('days')

// 表格列定义
const tableColumns = [
    {
        title: '操作描述',
        dataIndex: 'description'
    },
    {
        title: '用户类型',
        dataIndex: 'user_type',
        slot: true,
        align: 'center'
    },
    {
        title: '操作人',
        dataIndex: 'operator_name'
    },
    {
        title: '请求方法',
        dataIndex: 'method',
        slot: true,
        align: 'center'
    },
    {
        title: '控制器/方法',
        customRender: ({ record }) => `${record.controller}/${record.action}`
    },
    {
        title: '状态',
        dataIndex: 'is_success',
        slot: true,
        align: 'center'
    },
    {
        title: '响应时间',
        dataIndex: 'duration',
        slot: true
    },
    {
        title: 'IP地址',
        dataIndex: 'ip'
    },
    {
        title: '操作时间',
        dataIndex: 'created_at'
    },
    {
        title: '操作',
        dataIndex: 'action',
        slot: true,
        align: 'center'
    }
]

// 获取日志数据的API函数（用于DataList组件）
const getLogsApi = async (params) => {
    // 合并搜索条件
    const searchParams = {
        ...params,
        ...searchForm
    }
    return await getLogs(searchParams)
}

const fetchStatistics = async () => {
    try {
        const response = await getStatistics({ days: 7 })
        if (response.code === 200) {
            statistics.value = response.result
        }
    } catch (error) {
        console.error('获取统计数据失败:', error)
    }
}

const handleSearch = (searchData) => {
    // 更新搜索表单数据
    Object.assign(searchForm, searchData)
    DataListRef.value?.refreshData()
}

const handleReset = (resetData) => {
    // 更新搜索表单数据
    Object.assign(searchForm, resetData)
    DataListRef.value?.refreshData()
}



const showDetail = async (record) => {
    try {
        const response = await getLogDetail({ id: record.id })
        if (response.code === 200) {
            currentLog.value = response.result
            detailVisible.value = true
        }
    } catch (error) {
        message.error('获取日志详情失败')
    }
}

const showClearModal = () => {
    clearVisible.value = true
}

const handleClearLogs = async () => {
    clearLoading.value = true
    try {
        const params = clearType.value === 'all' ? { all: true } : { days: clearDays.value }
        const response = await clearLogs(params)
        if (response.code === 200) {
            message.success(response.message)
            clearVisible.value = false
            refreshData()
        }
    } catch (error) {
        message.error('清理日志失败')
    } finally {
        clearLoading.value = false
    }
}

const refreshData = () => {
    DataListRef.value?.refreshData()
    fetchStatistics()
}

const getMethodColor = (method) => {
    const colors = {
        'GET': 'blue',
        'POST': 'green',
        'PUT': 'orange',
        'DELETE': 'red',
        'PATCH': 'purple'
    }
    return colors[method] || 'default'
}

const getUserTypeColor = (userType) => {
    const colors = {
        'admin': 'blue',
        'user': 'green',
        'guest': 'default'
    }
    return colors[userType] || 'default'
}

// 生命周期
onMounted(() => {
    fetchStatistics()
})
</script>

<style lang="less" scoped>
.logs-container {
    padding: 24px;

    .stats-cards {
        margin-bottom: 24px;
    }


    .log-detail {
        .request-data {
            margin-top: 16px;

            h4 {
                margin-bottom: 8px;
                color: #1890ff;
            }

            pre {
                background: #f5f5f5;
                padding: 12px;
                border-radius: 4px;
                max-height: 200px;
                overflow-y: auto;
            }
        }

        .user-agent {
            margin-top: 16px;

            h4 {
                margin-bottom: 8px;
                color: #1890ff;
            }

            p {
                background: #f5f5f5;
                padding: 8px;
                border-radius: 4px;
                word-break: break-all;
            }
        }
    }

    .slow-request {
        color: #ff4d4f;
        font-weight: bold;
    }
}
</style>